package principal;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.LayoutStyle;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;

import persistence.ClienteDao;
import persistence.ConcessionariaDAO;
import algoritmos.BlockNestedLoopJoin;
import algoritmos.HashJoin;
import algoritmos.MergeJoin;
import beans.Cliente;
import beans.Concessionaria;

/**
 * Inteface gráfica obrigatória, criada no Netbeans.
 * @author Lucas Cavalcante, Fábio Theophilo
 */
public class TelaPrincipal extends JFrame {
	private static final long serialVersionUID = -3771993579377379269L;
	
	private JButton botaoIniciarValores;
	private JButton botaoRealizarJoin;
	private JButton botaoZerarTabelaJoin;
	private JComboBox comboAlgoritmos;
	private JPanel jPanel1;
	private JScrollPane jScrollPane1;
	private JScrollPane jScrollPane2;
	private JScrollPane jScrollPane3;
	private JSeparator jSeparator1;
	private JLabel labelNomeAlgoritmo;
	private JTable tabelaCliente;
	private JTable tabelaConcessionaria;
	private JTable tabelaJoin;
	private ClienteDao clientedao;
	private ConcessionariaDAO concessionariadao;
	private List<Cliente> listaClientes;
	private List<Concessionaria> listaConcessinaria;
	private String algoritmoEscolhido;

	public TelaPrincipal() {
		initComponents();
	}

	@SuppressWarnings("unchecked")
	private void initComponents() {

		jPanel1 = new JPanel();
		comboAlgoritmos = new JComboBox();
		botaoIniciarValores = new JButton();
		labelNomeAlgoritmo = new JLabel();
		jScrollPane1 = new JScrollPane();
		tabelaCliente = new JTable();
		jScrollPane2 = new JScrollPane();
		tabelaConcessionaria = new JTable();
		jSeparator1 = new JSeparator();
		jScrollPane3 = new JScrollPane();
		tabelaJoin = new JTable();
		botaoZerarTabelaJoin = new JButton();
		botaoRealizarJoin = new JButton();

		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		// setResizable(false);
		jScrollPane3
				.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

		comboAlgoritmos.setModel(new DefaultComboBoxModel(new String[] {
				"Block Nested Loop Join", "Merge Join", "Hash Join" }));
		comboAlgoritmos.setEnabled(false);
		comboAlgoritmos.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				comboAlgoritmosActionPerformed(evt);
			}
		});

		botaoIniciarValores.setText("Iniciar Valores");
		botaoIniciarValores.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				botaoIniciarValoresActionPerformed(evt);
			}
		});

		labelNomeAlgoritmo.setText("Algoritmos :");

		tabelaCliente.setModel(new DefaultTableModel(new Object[][] {
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null } },
				new String[] { "Codigo", "Nome", "CPF", "Endereco", "Numero",
						"DtNasc" }));
		tabelaCliente.setEnabled(false);
		jScrollPane1.setViewportView(tabelaCliente);

		tabelaConcessionaria.setModel(new DefaultTableModel(new Object[][] {
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null } },
				new String[] { "Codigo", "Nome", "CNPJ", "Endereco", "Numero",
						"Cod_Cliente" }));
		tabelaConcessionaria.setEnabled(false);
		jScrollPane2.setViewportView(tabelaConcessionaria);

		tabelaJoin.setModel(new DefaultTableModel(new Object[][] {
				{ null, null, null, null }, { null, null, null, null },
				{ null, null, null, null }, { null, null, null, null } },
				new String[] { "Codigo", "Nome", "CPF", "Endereco", "Numero",
						"DtNasc", "Codigo", "Nome", "CNPJ", "Endereco",
						"Numero", "CodigoCliente" }));
		tabelaJoin.setEnabled(false);
		jScrollPane3.setViewportView(tabelaJoin);

		botaoZerarTabelaJoin.setText("Zerar Tabela Join");
		botaoZerarTabelaJoin.setEnabled(false);
		botaoZerarTabelaJoin.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				botaoZerarTabelaJoinActionPerformed(evt);
			}
		});

		botaoRealizarJoin.setText("OK");
		botaoRealizarJoin.setEnabled(false);
		botaoRealizarJoin.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				botaoRealizarJoinActionPerformed(evt);
			}
		});

		GroupLayout jPanel1Layout = new GroupLayout(jPanel1);
		jPanel1.setLayout(jPanel1Layout);
		jPanel1Layout
		    .setHorizontalGroup(jPanel1Layout
		        .createParallelGroup(GroupLayout.Alignment.LEADING)
		        .addGroup(
		            jPanel1Layout
		            .createSequentialGroup()
		            .addGroup(
		                jPanel1Layout
		                .createParallelGroup(
		                    GroupLayout.Alignment.LEADING)
		                .addGroup(
		                    GroupLayout.Alignment.TRAILING,
		                    jPanel1Layout
		                    .createSequentialGroup()
		                    .addGap(32,
		                        32,
		                        32)
		                    .addGroup(
		                        jPanel1Layout
		                        .createParallelGroup(
		                            GroupLayout.Alignment.LEADING)
		                        .addGroup(
		                            jPanel1Layout
		                            .createSequentialGroup()
		                            .addComponent(
		                                jScrollPane1,
		                                GroupLayout.PREFERRED_SIZE,
		                                476,
		                                GroupLayout.PREFERRED_SIZE)
		                            .addPreferredGap(
		                                LayoutStyle.ComponentPlacement.RELATED,
		                                GroupLayout.DEFAULT_SIZE,
		                                Short.MAX_VALUE)
		                            .addComponent(
		                                jScrollPane2,
		                                GroupLayout.PREFERRED_SIZE,
		                                GroupLayout.DEFAULT_SIZE,
		                                GroupLayout.PREFERRED_SIZE)
		                            .addGap(28,
		                                28,
		                                28))
		                        .addGroup(
		                            jPanel1Layout
		                            .createSequentialGroup()
		                            .addGroup(
		                                jPanel1Layout
		                                .createParallelGroup(
		                                    GroupLayout.Alignment.LEADING,
		                                    false)
		                                .addGroup(
		                                    jPanel1Layout
		                                    .createSequentialGroup()
		                                    .addComponent(
		                                        botaoIniciarValores)
		                                    .addPreferredGap(
		                                        LayoutStyle.ComponentPlacement.UNRELATED)
		                                    .addComponent(
		                                        botaoZerarTabelaJoin))
		                                .addGroup(
		                                    jPanel1Layout
		                                    .createSequentialGroup()
		                                    .addComponent(
		                                        labelNomeAlgoritmo,
		                                        GroupLayout.PREFERRED_SIZE,
		                                        91,
		                                        GroupLayout.PREFERRED_SIZE)
		                                    .addPreferredGap(
		                                        LayoutStyle.ComponentPlacement.RELATED)
		                                    .addComponent(
		                                        comboAlgoritmos,
		                                        0,
		                                        GroupLayout.DEFAULT_SIZE,
		                                        Short.MAX_VALUE)))
		                            .addPreferredGap(
		                                LayoutStyle.ComponentPlacement.RELATED)
		                            .addComponent(
		                                botaoRealizarJoin)
		                            .addPreferredGap(
		                                LayoutStyle.ComponentPlacement.RELATED,
		                                GroupLayout.DEFAULT_SIZE,
		                                Short.MAX_VALUE))))
		                .addGroup(
		                    GroupLayout.Alignment.TRAILING,
		                    jPanel1Layout
		                    .createSequentialGroup()
		                    .addGap(0,
		                        0,
		                        Short.MAX_VALUE)
		                    .addComponent(
		                        jSeparator1,
		                        GroupLayout.PREFERRED_SIZE,
		                        1078,
		                        GroupLayout.PREFERRED_SIZE)))
		            .addContainerGap())
		        .addGroup(
		            GroupLayout.Alignment.TRAILING,
		            jPanel1Layout
		            .createSequentialGroup()
		            .addGap(0, 0, Short.MAX_VALUE)
		            .addComponent(jScrollPane3,
		                GroupLayout.PREFERRED_SIZE,
		                1040,
		                GroupLayout.PREFERRED_SIZE)
		            .addGap(17, 17, 17)));
		jPanel1Layout
		    .setVerticalGroup(jPanel1Layout
		        .createParallelGroup(GroupLayout.Alignment.LEADING)
		        .addGroup(
		            jPanel1Layout
		            .createSequentialGroup()
		            .addContainerGap()
		            .addGroup(
		                jPanel1Layout
		                .createParallelGroup(
		                    GroupLayout.Alignment.BASELINE)
		                .addComponent(
		                    botaoIniciarValores)
		                .addComponent(
		                    botaoZerarTabelaJoin))
		            .addGap(24, 24, 24)
		            .addGroup(
		                jPanel1Layout
		                .createParallelGroup(
		                    GroupLayout.Alignment.BASELINE)
		                .addComponent(
		                    labelNomeAlgoritmo,
		                    GroupLayout.PREFERRED_SIZE,
		                    39,
		                    GroupLayout.PREFERRED_SIZE)
		                .addComponent(
		                    comboAlgoritmos,
		                    GroupLayout.PREFERRED_SIZE,
		                    39,
		                    GroupLayout.PREFERRED_SIZE)
		                .addComponent(
		                    botaoRealizarJoin))
		            .addGap(18, 18, 18)
		            .addGroup(
		                jPanel1Layout
		                .createParallelGroup(
		                    GroupLayout.Alignment.LEADING)
		                .addComponent(
		                    jScrollPane1,
		                    GroupLayout.PREFERRED_SIZE,
		                    279,
		                    GroupLayout.PREFERRED_SIZE)
		                .addComponent(
		                    jScrollPane2,
		                    GroupLayout.PREFERRED_SIZE,
		                    279,
		                    GroupLayout.PREFERRED_SIZE))
		            .addGap(18, 18, 18)
		            .addComponent(jSeparator1,
		                GroupLayout.PREFERRED_SIZE,
		                GroupLayout.DEFAULT_SIZE,
		                GroupLayout.PREFERRED_SIZE)
		            .addGap(18, 18, 18)
		            .addComponent(jScrollPane3,
		                GroupLayout.PREFERRED_SIZE,
		                200, GroupLayout.PREFERRED_SIZE)
		            .addContainerGap(11, Short.MAX_VALUE)));

		GroupLayout layout = new GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout.createParallelGroup(
		    GroupLayout.Alignment.LEADING).addGroup(
		    GroupLayout.Alignment.TRAILING,
		    layout.createSequentialGroup()
		    .addComponent(jPanel1, GroupLayout.PREFERRED_SIZE,
		        GroupLayout.DEFAULT_SIZE,
		        GroupLayout.PREFERRED_SIZE)
		    .addGap(0, 0, Short.MAX_VALUE)));
		layout.setVerticalGroup(layout.createParallelGroup(
		    GroupLayout.Alignment.LEADING).addComponent(jPanel1,
		    GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE,
		    Short.MAX_VALUE));

		setResizable(false);
		setTitle("NP1-BD2 do Alex");
		pack();
	}// </editor-fold>

	private void comboAlgoritmosActionPerformed(ActionEvent evt) {
		// TODO add your handling code here:
	}

	private void botaoIniciarValoresActionPerformed(ActionEvent evt) {
		clientedao = new ClienteDao();
		concessionariadao = new ConcessionariaDAO();

		listaClientes = clientedao.listarClientes();
		listaConcessinaria = concessionariadao.listarConcessionarias();
		inicioBotoes();
		popularTabelaCliente(listaClientes);
		popularTabelaConcessionaria(listaConcessinaria);
	}

	private void botaoZerarTabelaJoinActionPerformed(ActionEvent evt) {
		this.tabelaJoin.setModel(new DefaultTableModel());
	}

	// TODO Ações
	private void botaoRealizarJoinActionPerformed(ActionEvent evt) {                                                  
    	List<Cliente> listaTempCliente = new ArrayList<Cliente>();
        List<Concessionaria> listaTempConcessinaria = new ArrayList<Concessionaria>();
        String[] titulos = new String [] {
        		"Codigo", "Nome", "CPF", "Endereco", "Numero", "DtNasc",
                "Codigo", "Nome", "CNPJ", "Endereco", "Numero", "CodigoCliente"
        };
    	
    	algoritmoEscolhido = String.valueOf(comboAlgoritmos.getSelectedItem());
        
    	if(algoritmoEscolhido.equals("Block Nested Loop Join")){
    		BlockNestedLoopJoin algoritmoBlockNested = new BlockNestedLoopJoin(clientedao.listarClientes(), concessionariadao.listarConcessionarias());
    		String[][] matrizBlockNested = algoritmoBlockNested.orderna();
    		
    		tabelaJoin.setModel(new DefaultTableModel(matrizBlockNested, titulos));
        }else if(algoritmoEscolhido.equals("Merge Join")){
        	MergeJoin algoritmoMerge = new MergeJoin(clientedao.listarClientes(), concessionariadao.listarConcessionarias());
        	String[][] matrizMerge = algoritmoMerge.orderna();
        	
        	tabelaJoin.setModel(new DefaultTableModel(matrizMerge, titulos));
        	
        }else{
        	HashJoin algoritmoHash = new HashJoin(clientedao.listarClientes(), concessionariadao.listarConcessionarias());
        	String[][] matrizHash = algoritmoHash.orderna();
        	
        	tabelaJoin.setModel(new DefaultTableModel(matrizHash,titulos));
        }
    }

	private void inicioBotoes() {
		botaoIniciarValores.setEnabled(false);
		botaoZerarTabelaJoin.setEnabled(true);
		botaoRealizarJoin.setEnabled(true);
		comboAlgoritmos.setEnabled(true);
		tabelaCliente.setEnabled(true);
		tabelaConcessionaria.setEnabled(true);
		tabelaJoin.setEnabled(true);
	}

	private void popularTabelaCliente(List<Cliente> lista) {
		String[][] object = new String[100][100];
		int i = 0;
		if (lista.size() != 0) {
			for (Cliente cliente : lista) {
				object[i][0] = String.valueOf(cliente.getCod());
				object[i][1] = cliente.getNome();
				// object[i][2] = cliente.getCpf();
				// object[i][3] = cliente.getEndereco();
				// object[i][4] = cliente.getNumero();
				// object[i][5] = cliente.getData().toString();

				i++;
				DefaultTableModel modelo = new DefaultTableModel(object,
						new String[] { "Codigo", "Nome", "CPF", "Endereco",
								"Numero", "DtNasc" });
				tabelaCliente.setModel(modelo);
			}
		}
	}

	private void popularTabelaConcessionaria(List<Concessionaria> lista) {
		String[][] object = new String[100][100];
		int i = 0;
		if (listaConcessinaria.size() != 0) {
			for (Concessionaria con : listaConcessinaria) {
				object[i][0] = String.valueOf(con.getCodigo());
				object[i][1] = con.getNome();
				object[i][2] = con.getCnpj();
				object[i][3] = con.getEndereco();
				object[i][4] = con.getNumero();
				object[i][5] = String.valueOf(con.getCodCliente());

				i++;
				DefaultTableModel modelo = new DefaultTableModel(object,
						new String[] { "Codigo", "Nome", "CNPJ", "Endereco",
								"Numero", "Cod_Cliente" });
				tabelaConcessionaria.setModel(modelo);
			}
		}
	}

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		try {
			for (UIManager.LookAndFeelInfo info : UIManager
					.getInstalledLookAndFeels()) {
				if ("Nimbus".equals(info.getName())) {
					UIManager.setLookAndFeel(info.getClassName());
					break;
				}
			}
		} catch (ClassNotFoundException ex) {
			java.util.logging.Logger.getLogger(TelaPrincipal.class.getName())
					.log(java.util.logging.Level.SEVERE, null, ex);
		} catch (InstantiationException ex) {
			java.util.logging.Logger.getLogger(TelaPrincipal.class.getName())
					.log(java.util.logging.Level.SEVERE, null, ex);
		} catch (IllegalAccessException ex) {
			java.util.logging.Logger.getLogger(TelaPrincipal.class.getName())
					.log(java.util.logging.Level.SEVERE, null, ex);
		} catch (UnsupportedLookAndFeelException ex) {
			java.util.logging.Logger.getLogger(TelaPrincipal.class.getName())
					.log(java.util.logging.Level.SEVERE, null, ex);
		}

		/* Create and display the form */
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new TelaPrincipal().setVisible(true);
			}
		});
	}
}
